package cn.sirun.com.fca.account.view.impl;

import android.app.Activity;
import android.content.Intent;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jungly.gridpasswordview.GridPasswordView;
import com.tencent.cloud.iov.kernel.constant.StatusCode;
import com.tencent.cloud.iov.kernel.model.BaseResponse;
import com.tencent.cloud.iov.router.Router;
import com.tencent.cloud.iov.util.ActivityUtils;
import com.tencent.cloud.iov.util.PatternMatchingUtils;
import com.tencent.cloud.iov.util.ResourcesUtils;
import com.tencent.cloud.iov.util.SRPUtils;
import com.tencent.cloud.iov.util.storage.TXCacheManager;
import com.tencent.cloud.uikit.ui.widget.IovToolbar;
import com.tencent.cloud.uikit.utils.SystemUiUtils;

import java.lang.ref.WeakReference;

import cn.sirun.com.fca.account.R;
import cn.sirun.com.fca.account.constant.AccountActivityConst;
import cn.sirun.com.fca.account.constant.AccountIntentConst;
import cn.sirun.com.fca.account.constant.AccountStatusCode;
import cn.sirun.com.fca.account.constant.CaptchaConst;
import cn.sirun.com.fca.account.constant.RequestParamConst;
import cn.sirun.com.fca.account.model.base.ResendResponse;
import cn.sirun.com.fca.account.model.base.SRPEncryptInfo;
import cn.sirun.com.fca.account.model.base.SubmitPhoneRequest;
import cn.sirun.com.fca.account.model.login.LoginResponse;
import cn.sirun.com.fca.account.model.register.RegisterSubmitResponse;
import cn.sirun.com.fca.account.model.register.SubmitEmailRequest;
import cn.sirun.com.fca.account.presenter.ICaptchaPresenter;
import cn.sirun.com.fca.account.presenter.impl.CaptchaPresenter;
import cn.sirun.com.fca.account.uitl.AccountStatusUtils;
import cn.sirun.com.fca.account.uitl.CountDownHandler;
import cn.sirun.com.fca.account.uitl.CountDownRunnable;
import cn.sirun.com.fca.account.uitl.IntentUtils;
import cn.sirun.com.fca.account.view.ICaptchaView;

public class CaptchaFlowView extends AccountBaseLoadingFlowView<ICaptchaPresenter>
        implements ICaptchaView {

    private static final String TAG = CaptchaFlowView.class.getSimpleName();

    private TextView mPhoneTV, mResendTV;
    private ImageView mErrorIV, mStepIV;
    private GridPasswordView mCaptchaGPV;

    private String mPhoneNumber;
    private int mFrom;
    private int mCountDown = 0;
    private CountDownHandler mCountDownHandler;
    private String mCaptchaCountDown;
    private String mResendCaptcha;
    private CaptchaRunnable mCaptchaRunnable;
    private String mSendString = "";
    private boolean mIsPhone;

    public CaptchaFlowView(Activity activity) {
        super(activity);
        mFrom = IntentUtils.getIntentFrom(getActivity().getIntent(), AccountIntentConst.REGISTER);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        setUpActionBar();
        initView();
    }

    public void onNewIntent(Intent intent) {
        if (null == intent) {
            return;
        }
    }

    @Override
    public void onRegSubmitCaptchaResult(BaseResponse<RegisterSubmitResponse> response) {
//        int code = response.getCode();
//        if (code == StatusCode.SUCCESS) {
//            RegisterSubmitResponse captchaResponse = response.getData();
//            String salt = captchaResponse.getSalt();
//            String group = captchaResponse.getGroup();
//
//            // 保存srp加密信息
//            if (!TextUtils.isEmpty(salt) && !TextUtils.isEmpty(group)) {
//                TXCacheManager.getInstance().put(SRPUtils.SRP_SALT, captchaResponse.getSalt());
//                TXCacheManager.getInstance().put(SRPUtils.SRP_GROUP, captchaResponse.getGroup());
//            }
//
//            Intent intent = Router.fromPath(AccountActivityConst.Path.PASSWORD);
//            getActivity().startActivity(intent);
//        } else {
//            handleCaptchaErrorCode(code);
//        }
        handleSubmitEmialCaptchaResult(response);
    }

    @Override
    public void onResendCaptchaResult(BaseResponse<ResendResponse> response) {
//        int code = response.getCode();
//        if (code == StatusCode.SUCCESS) {
//
//        } else {
//            handleCaptchaErrorCode(code);
//        }
        handleResendCaptchaResult(response);
    }

    @Override
    public void onRegSubmitEmialCaptchaResult(BaseResponse<RegisterSubmitResponse> response) {
        handleSubmitEmialCaptchaResult(response);
    }

    @Override
    public void onResendEmailCaptchaResult(BaseResponse<ResendResponse> response) {
//        int code = response.getCode();
//        if (code == StatusCode.SUCCESS) {
//            mCountDown = CaptchaConst.COUNT_DOWN;
//            if (null != response.getData()) {
//                mCountDown = response.getData().getResendTime();
//            }
//        } else {
//            handleCaptchaErrorCode(code);
//        }
        handleResendCaptchaResult(response);
    }

    @Override
    public void onResetSubmitCaptchaResult(BaseResponse<SRPEncryptInfo> response) {
        hideLoadingView();
        int code = response.getCode();
        if (StatusCode.SUCCESS != code) {
            handleCaptchaErrorCode(code);
            return;
        }
        SRPEncryptInfo srpEncryptInfo = response.getData();
        if (null != srpEncryptInfo) {
            String salt = srpEncryptInfo.getSalt();
            String group = srpEncryptInfo.getGroup();
            if (!TextUtils.isEmpty(salt) && !TextUtils.isEmpty(group)) {
                // 保存srp加密信息
                TXCacheManager.getInstance().put(SRPUtils.SRP_SALT, salt);
                TXCacheManager.getInstance().put(SRPUtils.SRP_GROUP, group);
            }
        }
        Intent intent = Router.fromPath(AccountActivityConst.Path.PASSWORD);
        intent.putExtra(AccountIntentConst.FROM, mFrom);
        intent.putExtra(AccountIntentConst.TELEPHONE, mPhoneNumber);
        getActivity().startActivity(intent);
    }

    private void handleResendCaptchaResult(BaseResponse<ResendResponse> response) {
        hideLoadingView();
        int code = response.getCode();
        if (code == StatusCode.SUCCESS) {
            mCountDown = CaptchaConst.COUNT_DOWN;
            if (null != response.getData()) {
                mCountDown = response.getData().getResendTime();
            }
        } else {
            handleCaptchaErrorCode(code);
        }
    }

    private void handleSubmitEmialCaptchaResult(BaseResponse<RegisterSubmitResponse> response) {
        hideLoadingView();
        int code = response.getCode();
        if (code == StatusCode.SUCCESS) {
            RegisterSubmitResponse captchaResponse = response.getData();
            String salt = captchaResponse.getSalt();
            String group = captchaResponse.getGroup();

            // 保存srp加密信息
            if (!TextUtils.isEmpty(salt) && !TextUtils.isEmpty(group)) {
                TXCacheManager.getInstance().put(SRPUtils.SRP_SALT, captchaResponse.getSalt());
                TXCacheManager.getInstance().put(SRPUtils.SRP_GROUP, captchaResponse.getGroup());
            }

            Intent intent = Router.fromPath(AccountActivityConst.Path.PASSWORD);
            intent.putExtra(AccountIntentConst.FROM, mFrom);
            intent.putExtra(AccountIntentConst.TELEPHONE, mPhoneNumber);
            getActivity().startActivity(intent);
        } else {
            handleCaptchaErrorCode(code);
        }
    }

    private void handleCaptchaErrorCode(int code) {
        if (AccountStatusCode.SMS_CAPTCHA_ERROR == code) {
            mResendTV.setText(ResourcesUtils.getString(R.string.tv_title_error_captcha));
            mErrorIV.setVisibility(View.GONE);
            return;
        }
        AccountStatusUtils.showToast(getActivity(), code);
    }

    @Override
    protected ICaptchaPresenter createPresenter() {
        return new CaptchaPresenter();
    }

    private void setUpActionBar() {
        final IovToolbar toolbar = SystemUiUtils.showActionBar(
                getActivity(), "");
        if (mFrom == AccountIntentConst.REGISTER) {
            toolbar.setHomeAsUpText(R.string.tv_title_previous_step);
        }
    }

    private void initView() {
        setContentView(R.layout.register_captcha_activity);
        final Activity activity = getActivity();
        mPhoneTV = activity.findViewById(R.id.tv_prompt_phone);
        mResendTV = activity.findViewById(R.id.tv_count_resend_promt);
        mErrorIV = activity.findViewById(R.id.iv_error_prompt);
        mStepIV = activity.findViewById(R.id.iv_step_two);

        mCaptchaGPV = activity.findViewById(R.id.gpv_captcha);

        mCaptchaGPV.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
            @Override
            public void onTextChanged(String psw) {
            }

            @Override
            public void onInputFinish(String psw) {
//                Intent intent = Router.fromPath(AccountActivityConst.Path.PASSWORD);
//                ActivityUtils.startActivityForResult(getActivity(), intent);
                showLoadingView();
                sendCaptchaRequest(psw);
            }
        });

        mResendTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleResendClick();
            }
        });
        initData(activity);
    }

    private void sendCaptchaRequest(String psw) {
        if (mIsPhone) {
            if (mFrom == AccountIntentConst.REGISTER) {
                getPresenter().submitCaptcha(psw);
            } else if (mFrom == AccountIntentConst.FORGET_PASSWORD) {
                getPresenter().resetSubmitCaptcha(psw);
            }
        } else {
            if (mFrom == AccountIntentConst.REGISTER) {
                getPresenter().submitEmialCaptcha(psw);
            } else if (mFrom == AccountIntentConst.FORGET_PASSWORD) {
                getPresenter().resetEmailSubmitCaptcha(psw);
            }

        }
    }

    private void handleResendClick() {
        if (mIsPhone) {
            if (mFrom == AccountIntentConst.REGISTER) {
                getPresenter().resendCaptcha();
            } else if (mFrom == AccountIntentConst.FORGET_PASSWORD) {
                getPresenter().resetResendCaptcha();
            }
        } else {
            if (mFrom == AccountIntentConst.REGISTER) {
                getPresenter().resendEmailCaptcha();
            } else if (mFrom == AccountIntentConst.FORGET_PASSWORD) {
                getPresenter().resetEmailResendCaptcha();
            }
        }
        mResendTV.setEnabled(false);
        mCaptchaRunnable.setCountDown(mCountDown);
        mCountDownHandler.sendMessage(new Message());
    }

    private void initData(Activity activity) {

        if (mFrom == AccountIntentConst.FORGET_PASSWORD) {
            mStepIV.setVisibility(View.GONE);
        }

        Intent intent = activity.getIntent();

        mCountDown = intent.getIntExtra(AccountIntentConst.COUNT_DOWN, CaptchaConst.COUNT_DOWN);
        if (intent.hasExtra(AccountIntentConst.TELEPHONE)) {
            mPhoneNumber = intent.getStringExtra(AccountIntentConst.TELEPHONE);
        }

        mCaptchaRunnable = new CaptchaRunnable(this, mCountDown);
        mCountDownHandler = new CountDownHandler(mCaptchaRunnable);
        mCountDownHandler.sendMessage(new Message());

        mCaptchaCountDown = ResourcesUtils.getString(R.string.tv_title_countdown_captcha);
        mResendCaptcha = ResourcesUtils.getString(R.string.tv_title_repeat_captcha);
        mIsPhone = PatternMatchingUtils.isTelephoneCorrect(mPhoneNumber);

        if (mFrom == AccountIntentConst.REGISTER) {
            if (mIsPhone) {
                mSendString =
                        String.format(ResourcesUtils.getString(R.string.tv_title_send_captcha), mPhoneNumber);
            } else {
                mSendString =
                        String.format(ResourcesUtils.getString(R.string.tv_title_send_captcha_emial), mPhoneNumber);
            }
        }
        mPhoneTV.setText(mSendString);
        mCaptchaGPV.togglePasswordVisibility();
    }

    private static class CaptchaRunnable extends CountDownRunnable {

        private WeakReference<CaptchaFlowView> mCaptchaFlowView;

        public CaptchaRunnable(CaptchaFlowView captchaFlowView, int countDown) {
            super(countDown);
            mCaptchaFlowView = new WeakReference<>(captchaFlowView);
        }

        @Override
        public void run() {
            CaptchaFlowView captchaFlowView = mCaptchaFlowView.get();
            if (mCountDown > 0) {
                captchaFlowView.mResendTV.setText(
                        String.format(captchaFlowView.mCaptchaCountDown, mCountDown--));
                captchaFlowView.mResendTV.setTextColor(ResourcesUtils.getColor(R.color.grey_A8));
                captchaFlowView.mCountDownHandler.postDelayed(this, mInterval);
                captchaFlowView.mResendTV.setEnabled(false);
            } else {
                captchaFlowView.mResendTV.setText(captchaFlowView.mResendCaptcha);
                captchaFlowView.mResendTV.setTextColor(ResourcesUtils.getColor(R.color.login_register_text_color));
                captchaFlowView.mResendTV.setEnabled(true);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mCountDownHandler != null) {
            mCountDownHandler.destroy();
        }
    }
}
